package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.redis.redisService.IUserInfoRedisService;
import cn.wolfcode.luowowo.respository.UserInforRespository;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.AssertUtil;
import cn.wolfcode.luowowo.util.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

@Service
//@Transactional  暂时不管事务
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInforRespository userInforRespository;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public UserInfo get(String id) {
        Optional<UserInfo> optional = userInforRespository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    @Override
    public Boolean checkPhone(String phone) {
        UserInfo userInfo = userInforRespository.findByPhone(phone);
        return userInfo != null;
    }

    @Override
    public void regist(String phone, String nickname, String password,
                       String rpassword, String verifyCode) {
        //1.判断参数是否为空
        AssertUtil.hasLength(phone, "手机号码不能为空");
        AssertUtil.hasLength(nickname, "昵称不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        AssertUtil.hasLength(rpassword, "重复密码不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");

        //2.判断密码是否一致
        AssertUtil.isEquals(password, rpassword, "密码不一致");

        //3.手机号格式是否正确
        boolean ret = AssertUtil.isPhone(phone);
        if (ret == false) {
            throw new LogicException("手机号码格式有误");
        } else {
            System.out.println("手机号码为: " + phone);
        }

        //4.判断手机号码是否已存在
        if (checkPhone(phone) == true) {
            throw new LogicException("手机号码已存在");
        }

        //5.验证码的检验
        String redisVerifyCode = userInfoRedisService.getVerifyCode(phone);
        if (redisVerifyCode == null) {
            throw new LogicException("验证码超时,已过期");
        }
        if (!redisVerifyCode.equals(verifyCode)) {
            throw new LogicException("验证码不正确");
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setEmail("");
        userInfo.setPassword(password);//必须加密
        userInfo.setGender(UserInfo.GENDER_SECRET);//性别保密
        userInfo.setLevel(1);
        userInfo.setCity("");
        userInfo.setHeadImgUrl("");
        userInfo.setInfo("");
        userInfo.setState(UserInfo.STATE_NORMAL);//明确写明状态
        userInfo.setId("");

        //模拟bug
      /*  UserInfo userInfo1=null;
        String city = userInfo1.getCity();*/

        //插入用户
        userInforRespository.insert(userInfo);

    }

    @Override
    public void sendVerifyCode(String phone, String url, String appkey) {
        //过去缓存中的计数器
        String counter = userInfoRedisService.getCounter();
        //如果计数器为空 设置新的计数器
        if (counter == null) {
            userInfoRedisService.setCounter();
        }
        //如果计数器不为空 而且值>0 (剩余次数大于0)
        if (counter != null && Integer.valueOf(counter) == 0) {
            throw new LogicException("验证码次数过多,请稍后再试");
        }

        //生成验证码
        String code = UUID.randomUUID().toString().substring(0, 4);
        StringBuilder builder = new StringBuilder(80);
        builder.append("您好,您的注册验证码是:").append(code).
                append("请在").append(Consts.VERIFY_CODE_VAI_TIME).append("分钟内使用");
        //发送验证码
        System.out.println(builder);

        //发送完验证码 计数器 减一
        userInfoRedisService.CounterDecr();

        //Url:https://way.jd.com/chuangxin/dxjk?mobile=13559778445&content=
        // 【创信】你的验证码是：5873，3分钟内有效！&appkey=5fe021e6a13820ed8edc0bab294e5b65
       /* RestTemplate restTemplate = new RestTemplate();
        Map map = restTemplate.getForObject(url, Map.class, code, appkey);
        System.out.println(map);
        if (!map.get("code").equals("10000")) {
            throw new LogicException("短信发送失败");
        }*/
        //存到redis中
        userInfoRedisService.setVerifyCode(phone, code);
    }

    @Override
    public UserInfo userLogin(String username, String password) {
        //1.获取username和password 查询数据库 是否存在
        UserInfo userInfo = userInforRespository.findByPhoneAndPassword(username, password);
        if (userInfo == null) {
            throw new LogicException("用户名或密码错误");
        }
        userInfo.setPassword(null);//把密码设为null 再返回前端
        return userInfo;
    }

    @Override
    public List<UserInfo> list() {
        return userInforRespository.findAll();
    }

    @Override
    public List<UserInfo> getByCity(String city) {
        return userInforRespository.findByCity(city);
    }
}
